package com.anche.cywebnew.Controller.systemManager;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.unit.DataUnit;
import cn.hutool.core.util.StrUtil;
import com.anche.cywebnew.DAO.configManager.SysOptionMapper;
import com.anche.cywebnew.DAO.systemManager.TerminalMapper;
import com.anche.cywebnew.DAO.systemManager.UserMapper;
import com.anche.cywebnew.DTO.LoginDTO;
import com.anche.cywebnew.DTO.ModuleTreeDTO;
import com.anche.cywebnew.Pojo.systemManager.SysUser;
import com.anche.cywebnew.Pojo.systemManager.TerminalInfo;
import com.anche.cywebnew.Service.auditManager.LoginLogSercive;
import com.anche.cywebnew.Service.logManager.LogService;
import com.anche.cywebnew.Service.securityManager.SecurityLogService;
import com.anche.cywebnew.Service.systemManager.LoginService;
import com.anche.cywebnew.Service.systemManager.UserService;
import com.anche.cywebnew.Utils.DES.DESHelper;
import com.anche.cywebnew.Utils.ResponseBody.IResponseStatus;
import com.anche.cywebnew.Utils.ResponseBody.ResponseResult;
import com.anche.cywebnew.Utils.String.StringUtils;
import com.anche.cywebnew.Utils.annotation.OptLog;
import com.anche.cywebnew.Utils.enums.OptType;
import com.anche.cywebnew.Utils.result.ResultUtil;
import com.github.pagehelper.Page;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.*;


@Controller
@RequestMapping("/system/user")
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private LoginService loginService;

    @Autowired
    private LogService logService;

    @Autowired
    private LoginLogSercive loginLogSercive;

    @Autowired
    private TerminalMapper terminalMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SecurityLogService securityLogService;

    @Autowired
    private EhCacheManager ehCacheManager;

    @Autowired
    private SysOptionMapper optionMapper;

    @GetMapping("/toPassword")
    public String toPassword() {
        return "/systemManager/password";
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult login(LoginDTO loginDTO, @RequestParam(value = "rememberMe", required = false) boolean rememberMe, HttpServletRequest request) {
        ResponseResult responseResult = new ResponseResult();
        if (loginDTO != null) {
            if (!StringUtils.isBlank(loginDTO.getLoginname())) {
                if (!StringUtils.isBlank(loginDTO.getPassword())) {
                    String loginName = DESHelper.base64Decrypt(loginDTO.getLoginname(), "12345678");
                    SysUser sysUser = userService.findUserByLoginName(loginName);
                    if (sysUser != null) {
                        //前端传来的数据解密
                        String password = DESHelper.base64Decrypt(loginDTO.getPassword(), "12345678");
                        TerminalInfo terminalInfo = userService.findTerminalByIp(request);
                        int eTimes = 0;
                        int ipTimes = 0;
                        Date dateNow = new Date();
                        String ip = terminalInfo.getTerminal_id();
                        if (sysUser.getErrortimes() != null) {
                            eTimes = sysUser.getErrortimes();
                        }
                        if (terminalInfo.getNum_id() != null && terminalInfo.getFail_times() != null) {
                            ipTimes = terminalInfo.getFail_times();
                        } else if (terminalInfo.getNum_id() == null) {
                            terminalInfo.setNum_id(UUID.randomUUID().toString().replaceAll("-", ""));
                            terminalInfo.setCreate_time(dateNow);
                            terminalInfo.setIslocked("0");
                            terminalInfo.setFail_times(ipTimes);
                            terminalInfo.setUpdate_time(dateNow);
                            terminalInfo.setJyw(DigestUtils.md5Hex(terminalInfo.getTerminal_id() + terminalInfo.getIslocked()));
                            terminalMapper.insertTerminal(terminalInfo);
                        }
                        responseResult = loginService.checkBlackIP(ip);
                        if (responseResult.getCode().equals("0")) {
                            return responseResult;
                        }
                        //用户状态校验
                        responseResult = loginService.chekUserState(sysUser);
                        if (responseResult.getCode().equals("0")) {
                            return responseResult;
                        }
                        //IP范围设置校验
                        responseResult = loginService.checkRangeIP(sysUser, ip);
                        if (responseResult.getCode().equals("0")) {
                            return responseResult;
                        }
                        //用户信息校验
                        responseResult = loginService.checkUserData(sysUser);
                        if (responseResult.getCode().equals("0")) {
                            return responseResult;
                        }
                        //用户工作时间校验
                        responseResult = loginService.checkWorkTime(sysUser);
                        if (responseResult.getCode().equals("0")) {
                            return responseResult;
                        }
                        // 账号有效期校验
                        Date zhyxq = sysUser.getZhyxq();
                        if(Objects.nonNull(zhyxq)){
                            if (isExpired(zhyxq)){
                                responseResult.setCode("0");
                                responseResult.setMessage("账号已超过有效期，请联系管理员");
                                return responseResult;
                            }
                        }
                        // 密码有效期校验
                        Date mmyxq = sysUser.getMmyxq();
                        if(Objects.nonNull(mmyxq)){
                            if (isExpired(mmyxq)){
                                responseResult.setCode("3");
                                responseResult.setMessage("密码已超过有效期，请修改密码！");
                                return responseResult;
                            }
                        }
                        // 用户高频访问
                        Map<String, String> result = loginLogSercive.checkHeightFW(ip);
                        if ("0".equals(result.get("code"))){
                            responseResult.setCode("0");
                            responseResult.setMessage(result.get("msg"));
                            securityLogService.insertSecurityLog("用户登录", result.get("msg"), sysUser);
                            return responseResult;
                        }
                        // 用户长时间未登录
                        String yjtime = optionMapper.getOptionValue("安全策略", "LongTimeLogin", "1");
                        yjtime = StringUtils.isBlank(yjtime) ? "6" : yjtime;
                        Date scdlsj = sysUser.getScdlsj();
                        if (scdlsj != null) {
                            Date now = new Date();
                            Integer iyjtime = Integer.parseInt(yjtime);
                            long igqsj = (now.getTime() - scdlsj.getTime()) / 1000 / 3600 / 24 / 30;
                            if (igqsj > iyjtime) {
                                securityLogService.insertSecurityLog("用户登录", "用户【"+ sysUser.getLoginname() + "】长时间未登录", sysUser);
                            }
                        }

                        Cache<String, Deque<Serializable>> cache = ehCacheManager.getCache("shiro-kickout-session");
                        String maxMutil = optionMapper.getOptionValue("安全策略", "maxMutil", "1");
                        maxMutil = StrUtil.isBlank(maxMutil) ? "10" : maxMutil;
                        int count = 0;
                        Set<String> keys = cache.keys();
                        for (String key : keys){
                            Deque<Serializable> deque = cache.get(key);
                            count += deque.size();
                        }
                        if (count > Integer.parseInt(maxMutil)){
                            responseResult.setCode("0");
                            responseResult.setMessage("已达用户最大并发数，不允许登录");
                            return responseResult;
                        }
                        if (5==sysUser.getStatus()){
                            responseResult.setCode("3");
                            responseResult.setMessage("初次修改密码，修改密码");
                            return responseResult;
                        }


                        try {
                            // 2、 Subject调用login
                            Subject subject = SecurityUtils.getSubject();
                            AuthenticationToken token = new UsernamePasswordToken(loginName, DigestUtils.md5Hex(password), rememberMe);

                            ((UsernamePasswordToken) token).setRememberMe(rememberMe);
                            subject.login(token);
                            String loginTimeOut = optionMapper.getOptionValue("安全策略", "LoginTimeOut", "1");
                            loginTimeOut = StringUtils.isBlank(loginTimeOut) ? "60" : loginTimeOut;
                            subject.getSession().setTimeout(1000 * 60 * Integer.parseInt(loginTimeOut));  // 设置session过期时间

                            userService.userSucessLogin(request, loginName);
                            logService.insertLogInfo("登录成功", "登陆", "1", sysUser.getId(), sysUser.getName(), sysUser.getOrgan());
                        } catch (UnknownAccountException e) {
                            eTimes = eTimes + 1;
                            ipTimes = ipTimes + 1;
                            String ms = loginService.LockMsg(eTimes, sysUser);
                            ms = ms + loginService.IPLockMsg(ipTimes, terminalInfo, sysUser);
                            logService.insertLogInfo(ms + ",账号不存在：{}" + e.getMessage(), "登陆", "0", sysUser.getId(), sysUser.getName(), sysUser.getOrgan());
                            responseResult.setCode("0");
                            responseResult.setMessage("账号或密码不正确。" + ms);
                            return responseResult;
                        } catch (DisabledAccountException e) {
                            eTimes = eTimes + 1;
                            ipTimes = ipTimes + 1;
                            String ms = loginService.LockMsg(eTimes, sysUser);
                            ms = ms + loginService.IPLockMsg(ipTimes, terminalInfo, sysUser);
                            logService.insertLogInfo(ms + ",账号未启用：{}" + e.getMessage(), "登陆", "0", sysUser.getId(), sysUser.getName(), sysUser.getOrgan());
                            responseResult.setCode("0");
                            responseResult.setMessage("账号或密码不正确。" + ms);
                            return responseResult;
                        } catch (IncorrectCredentialsException e) {
                            eTimes = eTimes + 1;
                            ipTimes = ipTimes + 1;
                            String ms = loginService.LockMsg(eTimes, sysUser);
                            ms = ms + loginService.IPLockMsg(ipTimes, terminalInfo, sysUser);
                            logService.insertLogInfo(ms + ",密码错误：{}" + e.getMessage(), "登陆", "0", sysUser.getId(), sysUser.getName(), sysUser.getOrgan());
                            responseResult.setCode("0");
                            responseResult.setMessage("账号或密码不正确。" + ms);
                            return responseResult;
                        } catch (RuntimeException e) {
                            eTimes = eTimes + 1;
                            ipTimes = ipTimes + 1;
                            String ms = loginService.LockMsg(eTimes, sysUser);
                            ms = ms + loginService.IPLockMsg(ipTimes, terminalInfo, sysUser);
                            logService.insertLogInfo(ms + ",未知错误,请联系管理员：{}" + e.getMessage(), "登陆", "0", sysUser.getId(), sysUser.getName(), sysUser.getOrgan());
                            responseResult.setCode("0");
                            responseResult.setMessage("账号或密码不正确。" + ms);
                            return responseResult;
                        }
                    } else {
                        responseResult.setCode("5");
                        responseResult.setMessage("用户名不存在");
                    }
                } else {
                    responseResult.setCode(IResponseStatus.ResponseStatus.PARAMERROR.getCode());
                    responseResult.setMessage("密码不能为空！");
                }
            } else {
                responseResult.setCode(IResponseStatus.ResponseStatus.PARAMERROR.getCode());
                responseResult.setMessage("用户名不能为空！");
            }
        } else {
            responseResult.setCode(IResponseStatus.ResponseStatus.PARAMERROR.getCode());
            responseResult.setMessage(IResponseStatus.ResponseStatus.PARAMERROR.getMessage());
        }
        return responseResult;
    }


    @Autowired
    private EnterpriseCacheSessionDAO enterpriseCacheSessionDAO;

    @Autowired
    private CacheManager shiroEhcacheManager;
    @RequestMapping("/logout")
    @ResponseBody
    public Object logout() {
        try {
            Subject currentUser = SecurityUtils.getSubject();

            SysUser existUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
            Session currentUserSession = currentUser.getSession(true); // 如果会话不存在则创建
            String currSessionId = String.valueOf(currentUserSession.getId());
            try {
                Collection<Session> sessions = enterpriseCacheSessionDAO.getActiveSessions();
                for (Session session : sessions) {
                    Serializable sessionId = session.getId();
                    if (sessionId.equals(currSessionId)) {
                        session.setTimeout(0);
                        shiroEhcacheManager.getCache("shiro-kickout-session").remove(existUser.getLoginname());
                        break;
                    }
                }
                logger.info("踢出用户：[{}]成功", existUser.getLoginname());
            } catch (Exception e) {
                currentUser.logout();
                logger.info("踢出用户：[{}]异常<{}>", existUser.getLoginname(), e);
            }
            return ResultUtil.success();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(0, e.getMessage());
        }
    }


    /**
     * 根据用户id查询权限树数据
     *
     * @return PermTreeDTO
     */
    @RequestMapping(value = "/getUserPerms", method = RequestMethod.POST)
    @ResponseBody
    public List<ModuleTreeDTO> getUserPerms() {
        List<ModuleTreeDTO> pvo = null;
        SysUser existUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
        if (null == existUser) {
            logger.debug("根据用户id查询限树列表！用户未登录");
            return pvo;
        }
        try {
            pvo = userService.getUserPerms(existUser.getId());
            //生成页面需要的json格式
            logger.debug("根据用户id查询限树列表查询=pvo:" + pvo);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("根据用户id查询权限树列表查询异常！", e);
        }
        return pvo;
    }

    @GetMapping("/loginName")
    @ResponseBody
    public ResponseResult getLoginName() {
        ResponseResult responseResult = new ResponseResult();
        try {
            SysUser existUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
            String LoginName = userMapper.selectLoginNameById(existUser.getId());
            responseResult.setCode("1");
            responseResult.setObj(LoginName);
        } catch (Exception e) {
            e.printStackTrace();
            responseResult.setCode("0");
            responseResult.setMessage("获取首页用户名异常");
            responseResult.setObj(e.getMessage());
        }
        return responseResult;
    }

    @GetMapping("/manager")
    public String toUserPage() {
        return "/systemManager/user";
    }

    @GetMapping("/userPager")
    @ResponseBody
    public Object getUserTable(@RequestParam("page") Integer page, @RequestParam("limit") Integer limit, SysUser sysUser) {
        Map<String, Object> map = new HashMap<>();
        try {
            Page<SysUser> sysUsers = userService.getUserPager(page, limit, sysUser);
            logger.info("<查询用户列表成功>");
            map.put("code", "0");
            map.put("count", sysUsers.getTotal());
            map.put("msg", "查询成功");
            map.put("data", sysUsers);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("<查询用户列表异常:{}>", e);
            map.put("code", "1");
            map.put("msg", e.getMessage());
        }
        return map;
    }

    @PostMapping("/userInfo")
    @ResponseBody
    @OptLog(title = "新增用户信息", type = OptType.ADD)
    public Object addUser(SysUser sysUser) {
        try {
            sysUser.setStatus(5);
            userService.addUser(sysUser);
            logger.info("<新增用户[{}]成功>", sysUser.getLoginname());
            return ResultUtil.success("新增用户成功");
        } catch (Exception e) {
            e.printStackTrace();
            if (e.getMessage().indexOf("CYUSERNEW3.UNILOGINNAME") != -1) {
                return ResultUtil.error(0, "登录名重复");
            }
            if (e.getMessage().indexOf("CYUSERNEW3.USER_SFZHM") != -1) {
                return ResultUtil.error(0, "身份号码重复");
            }
            if (e.getMessage().indexOf("CYUSERNEW3.USER_JYBH") != -1) {
                return ResultUtil.error(0, "警员编号重复");
            }
            logger.error("<新增用户[{}]异常:[{}]>", sysUser.getLoginname(), e);
            return ResultUtil.error(0, e.getMessage());
        }
    }

    @PutMapping("/userInfo")
    @ResponseBody
    @OptLog(title = "更新用户信息", type = OptType.UPDATE)
    public Object setUser(SysUser sysUser) {
        try {
            SysUser userByLoginName = userService.findUserByLoginName(sysUser.getLoginname());
            if (Objects.nonNull(userByLoginName)){
                long zhdays = DateUtil.between(userByLoginName.getZhyxq(), sysUser.getZhyxq(), DateUnit.DAY);
                StringBuilder sbuilder = new StringBuilder("用户【");
                sbuilder.append(sysUser.getLoginname()).append("】");
                if(zhdays > 0){
                    sbuilder.append("延长账号有效期【").append(zhdays).append("】天");
                    securityLogService.insertSecurityLog("账户有效期", sbuilder.toString(), sysUser);
                }else if (zhdays < 0){
                    sbuilder.append("缩短账号有效期【").append(zhdays).append("】天");
                    securityLogService.insertSecurityLog("账户有效期", sbuilder.toString(), sysUser);
                }
                userService.setUser(sysUser);
                logger.info("<更新用户[{}]成功>", sysUser.getLoginname());
                return ResultUtil.success("更新用户成功");
            }else {
                logger.info("<更新用户[{}]失败：用户不存在>", sysUser.getLoginname());
                return ResultUtil.success("更新用户失败：用户不存在");
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (e.getMessage().indexOf("TEST.USER_LOGINNAME") != -1) {
                return ResultUtil.error(0, "登录名重复");
            }
            if (e.getMessage().indexOf("TEST.USER_SFZHM") != -1) {
                return ResultUtil.error(0, "身份号码重复");
            }
            if (e.getMessage().indexOf("TEST.USER_JYBH") != -1) {
                return ResultUtil.error(0, "警员编号重复");
            }
            logger.error("<更新用户[{}]异常:[{}]>", sysUser.getLoginname(), e);
            return ResultUtil.error(0, e.getMessage());
        }
    }

    @DeleteMapping("/userInfo")
    @ResponseBody
    @OptLog(title = "删除用户信息", type = OptType.DEL)
    public Object delUser(@RequestParam("id") String id) {
        try {
            userService.delUser(id);
            logger.info("<删除id为[{}]的用户成功>", id);
            return ResultUtil.success("删除用户成功");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("<删除id为[{}]的用户异常：[{}]>", id, e);
            return ResultUtil.error(0, e.getMessage());
        }
    }

    @PutMapping("/status")
    @ResponseBody
    @OptLog(title = "更新用户锁定状态信息", type = OptType.UPDATE)
    public Object setStatus(@RequestParam("id") String id, @RequestParam("status") Integer status) {
        try {
            SysUser sysUser = new SysUser();
            sysUser.setStatus(status);
            sysUser.setId(id);
            SysUser loginUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
            SysUser curruser = userMapper.getUserById(id);
            if (Objects.nonNull(curruser)) {
                // 登录名，姓名，身份证号码用于生成新的校验位
                sysUser.setLoginname(curruser.getLoginname());
                sysUser.setName(curruser.getName());
                sysUser.setSfzhm(curruser.getSfzhm());

                userService.setUser(sysUser);
                if(status == 5)
                    securityLogService.insertSecurityLog("用户解锁", "用户【" + curruser.getLoginname() + "】解锁成功", loginUser);
                else if (status == 1){
                    securityLogService.insertSecurityLog("用户锁定", "用户【" + curruser.getLoginname() + "】锁定成功", loginUser);
                }
                logger.info("<更新id为[{}]的用户成功>", id);
                return ResultUtil.success("更新用户成功");
            }else {
                logger.info("未找到用户ID为[{}]的用户，更新失败",id);
                return ResultUtil.error(0, String.format("未找到用户ID为[{}]的用户，更新失败",id));
            }


        } catch (Exception e) {
            e.printStackTrace();
            logger.error("<更新id为[{}]的用户异常：[{}]>", id, e);
            return ResultUtil.error(0, e.getMessage());
        }
    }

    @PutMapping("/password")
    @ResponseBody
    @OptLog(title = "更新用户密码信息", type = OptType.UPDATE)
    public Object setPassword(@RequestParam("newpassword") String newpassword, @RequestParam("oldpassword") String oldpassword, @RequestParam("confirmpassword") String confirmpassword) {
        try {
            SysUser existUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
            if (existUser.getPassword().equals(DigestUtils.md5Hex(oldpassword))) {
                if (confirmpassword.equals(newpassword)) {
                    String newpwd = DigestUtils.md5Hex(newpassword);
                    existUser.setPassword(newpwd);
                    userService.setUser(existUser);
                    Subject currentUser = SecurityUtils.getSubject();
                    currentUser.logout();
                    return ResultUtil.success("密码修改成功，请重新登录");
                } else {
                    return ResultUtil.error(0, "新密码与确认密码不一致！");
                }
            } else {
                return ResultUtil.error(0, "原密码填写错误");
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("<更新密码异常：[{}]>", e);
            return ResultUtil.error(0, e.getMessage());
        }
    }
    @PutMapping("/resetPassword")
    @ResponseBody
    @OptLog(title = "重置用户密码信息", type = OptType.UPDATE)
    public Object resetPassword(@RequestParam("id") String id,@RequestParam("loginname") String loginname,
                                @RequestParam("name") String name,@RequestParam("sfzhm") String sfzhm,@RequestParam("status") int status) {
        try {
            SysUser existUser = new SysUser();
            existUser.setId(id);
            existUser.setLoginname(loginname);
            existUser.setName(name);
            existUser.setSfzhm(sfzhm);
            existUser.setStatus(status);

            String newpwd = DigestUtils.md5Hex("888888");
            existUser.setPassword(newpwd);
            userService.setUser(existUser);

            //踢出被重置密码用户
            try {
                Set<Object> keys = shiroEhcacheManager.getCache("shiro-kickout-session").keys();
                List<Map<Object, Object>> maps = new ArrayList<Map<Object, Object>>();
                for (Object object : keys) {
                    Map<Object, Object> map = new HashMap<Object, Object>();
                    Deque<Serializable> o = (Deque<Serializable>) shiroEhcacheManager.getCache("shiro-kickout-session").get(object);
                    Serializable sessionid = o.getLast();

                    if (loginname.equals(object)){
                        Collection<Session> sessions = enterpriseCacheSessionDAO.getActiveSessions();
                        for (Session session : sessions) {
                            Serializable sessionId = session.getId();
                            if (sessionId.equals(sessionid)) {
                                session.setTimeout(0);
                                shiroEhcacheManager.getCache("shiro-kickout-session").remove(loginname);
                                break;
                            }
                        }
                        logger.info("踢出用户：[{}]成功", loginname);
                        break;
                    }
                }
            }catch (Exception e){
                logger.info("踢出用户：[{}]异常<{}>", loginname, e);
            }

            return ResultUtil.success("密码修改成功。");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("<更新密码异常：[{}]>", e);
            return ResultUtil.error(0, e.getMessage());
        }
    }

    @PutMapping("/modifyPassword")
    @ResponseBody
//    @OptLog(title = "首次登录修改用户密码信息", type = OptType.UPDATE)
    public Object modifyPassword(@RequestParam("loginname") String loginname, @RequestParam("newpassword") String newpassword, @RequestParam("oldpassword") String oldpassword, @RequestParam("confirmpassword") String confirmpassword) {
        try {
            loginname = DESHelper.base64Decrypt(loginname, "12345678");
            newpassword = DESHelper.base64Decrypt(newpassword, "12345678");
            oldpassword = DESHelper.base64Decrypt(oldpassword, "12345678");
            confirmpassword = DESHelper.base64Decrypt(confirmpassword, "12345678");
            SysUser existUser = userMapper.getUserByLoginName(loginname);
            String oldpass = DigestUtils.md5Hex(oldpassword);
            if (Objects.nonNull(existUser) && existUser.getPassword().equals(oldpass)) {
                if (confirmpassword.equals(newpassword)) {
                    String newpwd = DigestUtils.md5Hex(newpassword);
                    existUser.setPassword(newpwd);
                    existUser.setStatus(0);
                    Date now = new Date();
                    if (DateUtil.compare(existUser.getMmyxq(), now) < 0){
                        DateTime offset = DateUtil.offset(now, DateField.MONTH, 1);  // 密码修改后自动延长一个月
                        existUser.setMmyxq(offset);
                    }
                    userService.setUser(existUser);
//                    Subject currentUser = SecurityUtils.getSubject();
//                    currentUser.logout();
                    securityLogService.insertSecurityLog("用户密码修改", "用户【" + existUser.getLoginname() + "】修改密码成功", existUser);
                    return ResultUtil.success("密码修改成功，请重新登录");
                } else {
                    return ResultUtil.error(0, "新密码与确认密码不一致！");
                }
            } else {
                return ResultUtil.error(0, "原密码或者账号填写错误");
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("<更新密码异常：[{}]>", e);
            return ResultUtil.error(0, e.getMessage());
        }
    }

    /**
     * 检查账号和密码是否过期
     * @param checkDate
     * @return
     */
    private boolean isExpired(Date checkDate){
        Date now = new Date();
        int com = now.compareTo(checkDate);

        if(com > 0){
            return true;
        }
        return false;
    }

}
